import java.net.*;
import java.io.*;
import java.util.*;

/*
 * Jason Lee (blujay)
 * EECS 382
 * P1B
 * SubmitClient.java
 */

public class SubmitClient {
	
	public static void failed()
	{
		// REQUIRES: n/a
		// MODIFIES: n/a
		// EFFECTS: default error output
		
        System.err.println("Submission unsuccessful");
        System.exit(1);
	}
	
	public static String[] getAssoc(String dir, final String type) {
		// REQUIRES: directory path and extension type, strings
		// MODIFIES: n/a
		// EFFECTS: retrieves all the files with user-provided extension
		//			in current directory
		
		File dirPath = new File(dir);
		if (!dirPath.isDirectory())
		{
			System.out.println("Invalid directory");
			return null;
		}
		FilenameFilter fnFilter = new FilenameFilter() {
			public boolean accept(File dir, String name)
			{
				return name.endsWith(type);
			}
		};
		return dirPath.list(fnFilter);
	}

	public static void main (String [] args) throws IOException
	{
		// SubmitClient main fxn
		
		int argsLength = args.length;
		if (argsLength < 3)
		{
			System.out.println("Insufficient info provided.");
			return;
		}
		int tempPntr = 3;
		int files = argsLength - tempPntr;
		Socket thisSocket = null;
		PrintWriter out = null;
		FileInputStream in = null;
		ArrayList<String> allFiles = null;
        for ( ; tempPntr != argsLength; tempPntr++)
        {
        	if (!args[tempPntr].startsWith("*."))
        	{
        		allFiles.add(args[tempPntr]);
        	} else {
        		// different handling for round
        		String dir = new File(".").getAbsolutePath();
        		String type = args[tempPntr].substring(2);
        		String [] fNames = getAssoc(dir,type);
        		for (String strIter : fNames)
        		{
        			allFiles.add(strIter);
        		}
        	}
        }
        files = allFiles.size();
		try
		{
        	thisSocket = new Socket(args[0],Integer.parseInt(args[1]));
            out = new PrintWriter(thisSocket.getOutputStream(), true);
            out.println(args[2]);
            out.println(files); // fix for file counting
            for (String thisFile : allFiles)
            {
            	File tempFile = new File(thisFile);
            	in = new FileInputStream(tempFile);
            	out.println(thisFile);
            	long size = tempFile.length();
            	out.println(size);
            	System.out.println("Submitting file " + args[tempPntr]);
            	for (long i = 0; i < size; i++)
            	{
            		out.println(in.read());
            	}
            }
            in.close();
			System.out.println("Submission successful: " + files + " files submitted");
		} catch (UnknownHostException e) {
            failed();
        } catch (IOException e) {
            failed();
        }
	}

}
